import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row, Col, Card, Icon, Tooltip, Form, Button, Input, Spin,
  Table, message, InputNumber, Modal, Select, Drawer,
} from 'antd';
import {
  learnKnowledgeRecommendQuestionRelation,
  knowledgeRecommendQuestionignore,
  knowledgerecommendquestiondelete,
  knowledgeRecommendQuestionBlacklist,
} from '@/services/capacityStudy';
import styles from './index.less';
import EditQa from '../../KnowledgeManagement/Overview/editQa';
import BackRouter from '@/pages/CapacityStudy/KnowledgeSmartMaintenance/backRouter';
const EditingKnowledge = React.lazy(() =>
  import('../../KnowledgeManagement/Overview/EditingKnowledge/editingKnowledge')
);
import RelatedKnowledgeV2 from '@/utils/RelatedKnowledgeV2';

const Search = Input.Search;
const FormItem = Form.Item;
const { confirm } = Modal;

class RecommendedTreatment extends Component {
  constructor(props) {
    super(props);
    this.state = {
      login: false,
      totala: 0,
      page: 1,
      pageSize: 10,
      similarList: [],
      query1: '', // 搜索的关键词
      minWordCount: '', // 最小字数
      maxWordCount: '', // 最大字数
      minAskCount: '', // 最小询问次数
      maxAskCount: '', // 最大询问次数
      order: 'count', // 排序字段
      sort: 'desc', //  排序方式，asc：升序，desc：降序,
      dxList: [],
      selectedRowKeys: [],
      selectedRows: [],
      item: [],
      // 关联参数
      logins: false,
      field: '1',
      query: '',
      pageA: '',
      pageSizeA: '',
      id: '', // 上下文参数
      loginjqr: false,
      zuid: '',
      shutRelevance: false,
      numberRadio: '1',
      pageSizetwo: 10,
      pagetwo: 1,
      nodeId: '',
      close: false,
      qaId: '',
      isUpdate: false,
      aALeng: '',
      glLeng: 10,
      questiona: '',
      total: 0,
      fromQaSId: '',
      fromQue: '',
      taskResultId: '',
      close: false,
      questions: [],
    };
  }

  componentDidMount() {
    const item = JSON.parse(this.props.location.query.item);
    this.setState({ item }, () => {
      this.knowledgeQuestionList();
    });
  }

  knowledgeQuestionList = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    const { item, page, pageSize, query1, minWordCount, maxWordCount, minAskCount, maxAskCount, order, sort } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeRecommendQuestionList',
        payload: { id: item.id, query: query1, order, sort, },
        callback: res => {
          if (res.length == 0) {
            this.setState({ query1: '', similarList: [], login: false });
          } else {
            this.setState({
              taskResultId: res[0].id, similarList: res, dxList: [],
              selectedRowKeys: [], selectedRows: [], login: false,
            });
          };
        },
      });
    });
  };

  knowledgeQuestionLists = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    const { item, page, pageSize, query1, minWordCount, maxWordCount, minAskCount, maxAskCount, order, sort } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeRecommendQuestionList',
        payload: { id: item.id, query: query1, order, sort, },
        callback: res => {
          this.setState({ similarList: res, dxList: [], selectedRowKeys: [], selectedRows: [], login: false, });
        },
      });
    });
  };

  knowledgeRecommendQuestionNext = () => {
    // 知识库智能维护 问题推荐 下一个 knowledgeRecommendQuestionNext
    this.setState({ query1: '' }, () => {
      this.props.form.setFields({ inputA: '' });
      const { dispatch, currentUser } = this.props;
      const { item } = this.state;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'knowledgeSmartMaintenance/knowledgeRecommendQuestionNext',
          payload: { order: 'count', sort: item.sort, taskId: item.taskId, id: item.id, },
          callback: res => {
            // message.success(`${res.msg}`);
            item.id = res.id;
            item.std = res.std;
            item.index = res.index;
            item.qaId = res.qaId;
            // item.index += 1;
            this.setState({ item, }, () => {
              this.knowledgeQuestionList();
            });
          },
        });
      });
    });
  };

  // 表单数据
  userInfo = () => {
    return this.props.form.getFieldsValue();
  };

  // 删除回调
  knowledgeQuestionDelete = ids => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeSmartMaintenance/knowledgeQuestionDelete',
        payload: { ids, },
        callback: res => {
          message.success(`${res.msg}`);
          this.setState({ login: false, selectedRowKeys: [] }, () => {
            this.knowledgeQuestionList();
          });
        },
      });
    });
  };

  // 引导黑名单回调
  knowledgeQuestionDelete = (ids, url) => {
    const { selectedRows, item } = this.state;
    if (selectedRows.length === 0) {
      message.error('请至少选择一项');
    } else {
      const a = [];
      selectedRows.map((item, index) => {
        a.push(item.question);
      });
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: url,
          payload: { question: a, id: item.id, },
          callback: res => {
            message.success(`${res.msg}`);
            this.setState({ login: false, selectedRowKeys: [], dxList: [], selectedRows: [], }, () => {
              this.knowledgeQuestionList();
            });
          },
        });
      });
    }
  };

  // 批量删除
  batchDelete = () => {
    const { selectedRows, item } = this.state;
    if (selectedRows.length === 0) {
      return message.error('请至少选择一项');
    };
    confirm({
      title: '确定删除选中的这些问题吗?',
      content: '',
      onOk: async () => {
        const res = await knowledgerecommendquestiondelete({
          resultId: item.id,
          questions: selectedRows.map(items => items.question),
        });
        message.success(res.msg);
        this.knowledgeQuestionList();
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  // 批量移到黑名单
  moveBlacklist = async () => {
    const { item, selectedRows } = this.state;
    if (selectedRows.length === 0) {
      return message.error('请至少选择一项');
    };
    const res = await knowledgeRecommendQuestionBlacklist({
      ids: selectedRows.map(items => items.id),
      resultId: item.id,
    });
    message.success(res.msg);
    this.knowledgeQuestionList();
  };

  // 添加到推荐知识点
  tatknowledgePoint = async () => {
    const { dxList, item, selectedRows } = this.state;
    if (selectedRows.length === 0) {
      return message.error('请至少选择一项');
    };
    const res = await learnKnowledgeRecommendQuestionRelation({
      resultId: item.id,
      qaId: item.qaId ? item.qaId : item.sid,
      ids: dxList,
    });
    message.success(`${res.message}`);
    this.knowledgeQuestionList();
  };

  // 添加为新知识点
  tbknowledgePoint = () => {
    const { dxList } = this.state;
    const { selectedRows, item } = this.state;
    if (selectedRows.length === 0) {
      message.error('请至少选择一项');
    } else {
      const arr = [];
      selectedRows.map(items => {
        arr.push(items.question.replace(/<.*?>/g, ''));
      });
      // this.formRef.initKnow();
      // this.setState({ questions: arr }, () => {
      //   this.setState({ close: true });
      // });
      this.EditingKnowledge.showEditDrawer(null, null, '', arr, selectedRows, '', 2);
    }
  };

  onClose = () => {
    const { dxList } = this.state;
    this.setState({ close: false, questions: [], }, () => {
      if (this.props.location.params == undefined) { } else {
        const item = this.props.location.params.item;
        this.setState({ item }, () => {
          this.knowledgeQuestionList();
        });
      }
    });
  };

  // 忽略
  lose = async () => {
    const { dxList, item, selectedRows } = this.state;
    if (selectedRows.length === 0) {
      return message.error('请至少选择一项');
    };
    const res = await knowledgeRecommendQuestionignore({ ids: dxList, resultId: item.id });
    message.success(`${res.message}`);
    this.knowledgeQuestionList();
  };

  // 排序
  pXhandleChange = (pagination, filters, sorter) => {
    if (sorter.field) { } else {
      this.setState({ order: 'count', sort: 'desc' }, () => {
        this.knowledgeQuestionList();
      });
    }
    if (sorter.field === 'count') {
      // 询问次数排序
      if (sorter.order === 'ascend') {
        // 升序
        this.setState({ order: 'count', sort: 'asc' }, () => {
          this.knowledgeQuestionList();
        });
      }
      if (sorter.order === 'descend') {
        // 降序
        this.setState({ order: 'count', sort: 'desc' }, () => {
          this.knowledgeQuestionList();
        });
      }
    }
    if (sorter.field === 'similarity') {
      // 相似度排序
      if (sorter.order === 'ascend') {
        // 升序
        this.setState({ order: 'accuracy', sort: 'asc', }, () => {
          this.knowledgeQuestionList();
        });
      }
      if (sorter.order === 'descend') {
        // 降序
        this.setState({ order: 'accuracy', sort: 'desc' }, () => {
          this.knowledgeQuestionList();
        });
      }
    }
  };

  /*
   * --------------关联页面交互------------------------
   */
  // 关联已有知识点
  tcknowledgePoint = () => {
    this.props.form.setFields({ businessName: '' });
    const { selectedRows, item } = this.state;
    if (selectedRows.length === 0) {
      message.error('请至少选择一项');
    } else {
      const a = [];
      selectedRows.map((item, index) => {
        a.push(item.id);
      });
      this.setState({ question: a[0], query: '' }, () => {
        this.RelatedKnowledge.openAndInit([])
        this.setState({ guanlianList: a });
      });
    }
  };

  setClassName = (record, index) => {
    return index < this.state.aALeng ? styles.red : '';
  };

  // 执行关联
  handleDelete = async data => {
    if (data.length == 0) {
      return false
    }
    const items = data[0]
    this.setState({ shutRelevance: false });
    const { guanlianList, item } = this.state;
    let qaType;
    switch (items.type) {
      case 1:
        qaType = 'qa';
        break;
      case 2:
        qaType = 'atlasNode';
        break;
      case 3:
        qaType = 'dialog';
        break;
      case 4:
        qaType = 'form';
        break;
    };
    const res = await learnKnowledgeRecommendQuestionRelation({
      resultId: item.id,
      qaId: items.id,
      ids: guanlianList,
      qaType,
    });
    message.success(`${res.msg}`);
    this.setState({ selectedRowKeys: [], dxList: [], selectedRows: [] });
    this.knowledgeQuestionList();
  };

  onRef = ref => {
    this.qaRef = ref;
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        const a = [];
        selectedRows.map((item, index) => {
          a.push(item.id);
        });
        this.setState({ dxList: a, selectedRowKeys, selectedRows });
      },
    };
    const columns = [
      {
        title: '问题',
        width: '300',
        dataIndex: 'question',
        render(item) {
          return <div dangerouslySetInnerHTML={{ __html: item }} />;
        },
      },
      {
        title: '询问次数',
        width: '100',
        sorter: (a, b) => { },
        dataIndex: 'count',
      },
      {
        title: '相似度',
        dataIndex: 'similarity',
        sorter: (a, b) => { },
        width: '200',
      },
    ];

    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <div style={{ minHeight: 'calc(100vh - 150px)', background: '#ffffff' }}>
            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10 }} xs={24}>
                <div className={styles.title}>
                  <span>推荐问题处理</span>
                  <BackRouter pathname="/capacity/knowledgeSmartMaintenance/problemRecommendedList"></BackRouter>
                </div>
              </Col>
            </Row>
            <Card bordered={false}>
              <div style={{ marginBottom: 20 }}>
                <Form layout="inline">
                  <FormItem
                    style={{ marginRight: 80, color: '#01c0f6', fontSize: 18 }}
                    label="推荐到知识点"
                  >
                    {this.state.item.std}
                  </FormItem>
                  <FormItem className="buttonYs">
                    <Button onClick={this.knowledgeRecommendQuestionNext}>下一个</Button>
                  </FormItem>
                </Form>
              </div>
              <div className={styles.border} />
              <Row>
                <Form style={{ marginBottom: 20 }} layout="inline">
                  <FormItem>
                    {getFieldDecorator('inputA', {
                      initialValue: this.state.query1,
                    })(
                      <Search
                        placeholder="请输入关键词"
                        onSearch={value => {
                          this.setState({ query1: value, }, () => {
                            this.knowledgeQuestionLists();
                          });
                        }}
                        style={{ width: 325 }}
                      />
                    )}
                  </FormItem>
                  <span style={{ float: 'right' }}>
                    <FormItem className="zdyButtonD">
                      <Button onClick={this.tatknowledgePoint} type="primary">添加到推荐知识点</Button>
                    </FormItem>
                    <FormItem className="zdyButtonZ">
                      <Button onClick={this.tbknowledgePoint} type="primary">添加为新知识点</Button>
                    </FormItem>
                    <FormItem className="zdyButtonZ">
                      <Button onClick={this.tcknowledgePoint} type="primary">关联已有知识点</Button>
                    </FormItem>
                    <FormItem className="zdyButtonZ">
                      <Button onClick={this.lose} type="primary">忽略</Button>
                    </FormItem>
                    <FormItem className="zdyButtonZ">
                      <Button onClick={this.batchDelete} type="primary">删除</Button>
                    </FormItem>
                    <FormItem className="zdyButtonB">
                      <Button onClick={this.moveBlacklist} type="primary">移到黑名单</Button>
                    </FormItem>
                  </span>
                </Form>
                <Spin spinning={this.state.login}>
                  <Table
                    className="zdyTable"
                    rowSelection={rowSelection}
                    onChange={this.pXhandleChange}
                    style={{ padding: '20px 0px 20px 0px' }}
                    columns={columns}
                    dataSource={this.state.similarList} // 数据
                    pagination={false}
                    rowKey="id"
                  // onChange={this.handleChange}
                  // pagination={{  // 分页
                  //   total: this.state.totala,
                  //   pageSize: this.state.pageSize,  // 显示几条一页
                  //   current: this.state.page, // 当前页
                  //   showSizeChanger: true,  // 是否显示可以设置几条一页的选项
                  //   showQuickJumper: true,
                  //   onChange: this.pageWay,
                  //   onShowSizeChange: this.onShowSizepageWay
                  // }}
                  />
                </Spin>
                <Form layout="inline">
                  <FormItem className="zdyButtonD">
                    <Button onClick={this.tatknowledgePoint} type="primary">
                      添加到推荐知识点
                    </Button>
                  </FormItem>
                  <FormItem className="zdyButtonZ">
                    <Button onClick={this.tbknowledgePoint} type="primary">
                      添加为新知识点
                    </Button>
                  </FormItem>
                  <FormItem className="zdyButtonZ">
                    <Button onClick={this.tcknowledgePoint} type="primary">
                      关联已有知识点
                    </Button>
                  </FormItem>
                  <FormItem className="zdyButtonZ">
                    <Button onClick={this.lose} type="primary">
                      忽略
                    </Button>
                  </FormItem>
                  <FormItem className="zdyButtonZ">
                    <Button onClick={this.batchDelete} type="primary">
                      删除
                    </Button>
                  </FormItem>
                  <FormItem className="zdyButtonB">
                    <Button onClick={this.moveBlacklist} type="primary">
                      移到黑名单
                    </Button>
                  </FormItem>
                </Form>
              </Row>
            </Card>
            {/* 添加为新知识点 */}
          </div>
          <Drawer
            title={<FormattedMessage id="app.overView.editQa" />}
            placement="right"
            closable
            onClose={this.onClose}
            visible={this.state.close}
            width={800}
            destroyOnClose
          >
            <EditQa
              taskResultId={this.state.taskResultId}
              addType="recommend"
              questions={this.state.questions}
              onClose={this.onClose}
            />
          </Drawer>
          <EditingKnowledge
            onRef={ref => (this.EditingKnowledge = ref)}
            refreshList={this.knowledgeQuestionList}
            categoryId={'/'}
            authority={2}
            ifCapacity={true}
          />
          <RelatedKnowledgeV2
            onRef={ref => this.RelatedKnowledge = ref}
            applicationId={''}
            chooseType='radio'
            handleModalOk={this.handleDelete}
          />
        </PageHeaderWrapper>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(RecommendedTreatment));
